<?php


namespace Hilaoyu\LaravelPrivateApi;



use Hilaoyu\LaravelExtend\Supports\Uuid;
use Hilaoyu\Utils\Traits\ErrorsTrait;
use Hilaoyu\Utils\UtilAes;
use Hilaoyu\Utils\UtilHttp;
use Illuminate\Support\Carbon;

class PrivateApiClient
{

    use ErrorsTrait;

    protected $client = null;
    protected $encryptor = null;
    protected $app_id = '';
    protected $resultCache=null;


    public function __construct($basic_uri='',$secret='',$app_id=''){
        $this->client = new UtilHttp($basic_uri);
        if($secret){
            $this->encryptor = UtilAes::make($secret);
        }
        $this->app_id = trim($app_id);
    }

    public function useSsl($cert, $key, $verify = false){
        $this->client->useSsl($cert,$key,$verify);
    }

    /**
     * @param $path 路径
     * @param array $data 加密数据
     * @param array $params 明文数据
     * @param string $method
     * @param array $headers
     * @return array|false|mixed
     * @throws \Exception
     */
    public function request($path,array $data=[],$params=[],$method="post",$headers=[]){
        $this->resultCache = null;

        $data['_timestamp'] = Carbon::now()->utc()->unix();
        $data['_data_id'] = Uuid::generate();

        if($this->encryptor){
            $data = $this->encryptor->encrypt($data);
            $params['data'] = $data;
        }else{
            $params = array_merge($params,$data);
        }



        if($this->app_id){
            $params['app_id'] = $this->app_id;
        }

        //dump($path,$params);
        $result = $this->client->httpRequestJson($path,$params,$method,$headers);

        if(!$result){
            $this->setError($this->client->getError());
            return false;
        }


        $result_data = data_get($result,'data');
        if(is_string($result_data) && !empty($result_data)){
            $result['data'] = $this->decrypt($result_data);
        }

        $this->resultCache = $result;
        $status = data_get($result,'status');
        if(!$status){
            $message = data_get($result,'message');
            if($message){
                $this->setError($message);
            }
            $errors = data_get($result,'errors');
            if(!empty($errors)){
                $this->setError($errors);
            }
        }

        return $status;
    }


    public function getResult($key='',$default=null){
        $key = trim($key);

        return $key ? data_get($this->resultCache,$key,$default) : $this->resultCache;
    }



    public function encrypt($payload){
        if($this->encryptor){
            $payload = $this->encryptor->encrypt($payload);
        }
        return $payload;
    }

    public function decrypt($payload){
        if($this->encryptor){
            $payload = $this->encryptor->decrypt($payload);
        }
        return $payload;
    }
}
